package com.msb.mall.ware.service.impl;

import com.msb.mall.common.constant.WareConstant;
import com.msb.mall.ware.entity.PurchaseDetailEntity;
import com.msb.mall.ware.entity.vo.MergeVO;
import com.msb.mall.ware.entity.vo.PurchaseDoneVO;
import com.msb.mall.ware.entity.vo.PurchaseItemDoneVO;
import com.msb.mall.ware.service.PurchaseDetailService;
import com.msb.mall.ware.service.WareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.mall.common.utils.PageUtils;
import com.msb.mall.common.utils.Query;

import com.msb.mall.ware.dao.PurchaseDao;
import com.msb.mall.ware.entity.PurchaseEntity;
import com.msb.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public Integer merge(MergeVO mergeVO) {
        Long purchaseId = mergeVO.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        PurchaseEntity byId = this.getById(purchaseId);
        if (byId.getStatus() > WareConstant.PurchaseStatusEnum.ASSIGED.getCode()) {
            return -1;
        }

        final Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> list = mergeVO.getItems().stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode());
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            return purchaseDetailEntity;
        }).filter(id ->{
            PurchaseDetailEntity item = purchaseDetailService.getById(id);
            return item.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode();
                }

        ).collect(Collectors.toList());
        if (list != null && list.size() > 0) {
            purchaseDetailService.updateBatchById(list);
        }

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(finalPurchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
        return 1;
    }

    @Transactional
    @Override
    public void receive(List<Long> ids) {
        // 1.找出采购单的状态为新建或者已分配
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(purchaseEntity -> {
            return purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGED.getCode();
        }).map(purchaseEntity -> {
            purchaseEntity.setUpdateTime(new Date());
            // 更新采购单的状态为已领取
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return purchaseEntity;
        }).collect(Collectors.toList());
        // 2.更新采购单的状态
        this.updateBatchById(purchaseEntities);
        // 3.更新采购单的明细的状态
        for (Long id : ids) {
            List<PurchaseDetailEntity> purchaseDetailEntities  =  purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", id));
            List<PurchaseDetailEntity> collect = purchaseDetailEntities.stream().map(item -> {
                item.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return item;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        }

    }

    @Transactional
    @Override
    public void done(PurchaseDoneVO vo) {
        // 获取采购单编号
        Long id = vo.getId();
        // 2.改变采购项的状态
        Boolean flag = true; // 记录采购的状态 默认为 完成
        List<PurchaseDetailEntity> list = new ArrayList<>();
        // 获取所有的的采购项
        List<PurchaseItemDoneVO> items = vo.getItems();
        for (PurchaseItemDoneVO item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                // 该采购项采购出现了问题
                flag = false;
                purchaseDetailEntity.setStatus(item.getStatus());
            } else {     // 该采购项采购成功
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 4.将采购成功的采购项进入入操作
                PurchaseDetailEntity purchaseDetailEntity1 = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(purchaseDetailEntity1.getSkuId(), purchaseDetailEntity1.getWareId(), purchaseDetailEntity1.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());

            list.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(list); // 批量更新采购项的状态
        // 3.改变采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        if (flag) {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        } else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

}